<?php
declare (strict_types=1);

namespace app\sysuser\controller\system;

use app\common\controller\SysBackend;
use app\common\enums\UserStatusEnum;
use app\common\model\banxi\sys\SysMenu as SysMenuModel;
use app\common\model\banxi\sys\SysRoleMenu;
use app\common\service\MenuService;
use ba\Exception;
use think\db\exception\DbException;
use think\db\exception\PDOException;
use think\exception\ValidateException;

class SysMenu extends SysBackend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new SysMenuModel();
    }


    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $sysRoleMenuModel = new SysRoleMenu();
        $list = $this->model->where($where)
            ->order(['id' => 'desc'])
            ->paginate([
                'page' => $pageParams['page'],
                'list_rows' => $pageParams['limit']
            ])->each(function ($item) use ($sysRoleMenuModel) {
                $item['menuIds'] = $sysRoleMenuModel->listMenuIdByRoleId($item['id']) ?? [];
            });
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('请传递你要查询的记录');
        }
        $where = get_query($param);
        $info = $this->model->with(['roleInfo'])->where($where)
            ->find();
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $this->ok('操作成功', removeNull($info));
    }

    public function bathSaveOrUpdate()
    {
        $param = $this->request->param();
        try {
            $menuService = new MenuService();
            $menuService->createMenu($param);
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }

    public function listTree()
    {
        try {
            $tree = $this->model->listTree();
        } catch (Exception|PDOException|ValidateException $e) {
            $this->fail($e->getMessage());
        }
        $this->ok('操作成功', $tree);
    }
}
